local base = _G
local math = base.math
module("gui")

CheckboxG = {}
CheckboxGMT = { __index = CheckboxG }

base.setmetatable(CheckboxG, { __index = ObjectG })

CheckboxG.create = function(x, y, text, is_checked)
  text = text or ""
  local styles = get_styles('font', 'padding')
  local colors = get_colors('font', 'border', 'background')
  local height = math.max(styles.font:get_height(), 12)
  local width = styles.font:get_width(text)+ height + styles.padding

  local self = Object(x, y, width, height, CheckboxGMT)

  self.styles = styles
  self.colors = colors

  self.text = text
  self.is_checked = is_checked or false
  self.is_down = false

  return self
end

CheckboxG.destroy = function(self)
  self.text = nil
  self.is_checked = nil
  self.is_down = nil
  
  self.styles = nil
  self.colors = nil
  ObjectG.destroy(self)
end

-- handle mouse input
CheckboxG.mouse_press = function(self, button, x, y)
  self.is_down = true
  self.is_checked = not (self.is_checked or false)
  self:on_change(self.is_checked)
end

CheckboxG.mouse_release = function(self, button, x, y)
  self.is_down = false
end

CheckboxG.redraw = function(self, delta)
  local c = self.node.canvas
  c:clear()

  local alpha = 0.5
  if self.is_down == true and self.is_hovered == true then
    alpha = 1
  elseif self.is_hovered == true then
    alpha = 0.75
  end

  -- draw background rectangle
  local sq = self.height
  local y = -self.height/2 - sq/2
  local l, t, r, b = 0, 0 + y, sq, sq + y
  c:rect(l - 1, t - 1, r + 1, b + 1)
  local a = alpha
  if self.is_focused then
    a = math.min(a*1.5, 1)
  end
  c:set_fill_style(self.colors.border, a)
  c:fill()
  c:rect(l, t, r, b)
  c:set_fill_style(self.colors.background, 1)
  c:fill()
--[[
  local grad = base.LinearGradient()
  grad:stop_point1(0, -self.height, self.colors.border)
  grad:stop_point2(0, 0, self.colors.background)
  c:rect(l, t, r, b)
  c:set_fill_style(grad, alpha)
  c:fill_gradient()
]]
  if self.is_checked ~= false then
    local a = alpha
    if self.is_checked == nil then
      a = a/4
    end
    c:move_to(2, 8 + y)
    c:line_to(6, 4 + y)
    c:line_to(14, 12 + y)
    c:set_line_style(2, self.colors.font, a)
    c:stroke()
  end
	
  -- write the text
  local out = self.text
  out = self.styles.font:clamp(out, self.width, "...")
  --local w = self.styles.font:get_width(out)
  c:set_font(self.styles.font, self.colors.font, alpha)
  -- baseline
  local bs =(self.height - self.styles.font:get_size())/2
  c:move_to(16 + self.styles.padding, -self.height + bs)
  c:write(out)
end

CheckboxG.update = function(self, dt)
  self:redraw(dt)
end

-- events
CheckboxG.on_change = function(self, value)

end

Checkbox = CheckboxG.create